import React, { useState, useEffect } from 'react';
import { Tabs,Toast } from 'antd-mobile'
import { UserCircleOutline } from 'antd-mobile-icons'
import { qding,shang ,deleteOrder,updateOrderStatus} from '../../https/index'
// 计算rem值的工具函数
const rem = (px) => `${px / 16}rem`;
const logid = sessionStorage.getItem("logid")
const Wan = () => {
    const [list, setList] = useState([])
    const [shlist, setShlist] = useState([])
    const getData = async () => {
        const res = await qding({logid})
        
        setList(res.data.orders)
    }


    const getShang = async()=>{
        const res = await shang({})
        setShlist(res.data.list)
    }
    useEffect(() => {
        getData()
        getShang()
    }, [])
// 删除订单功能
    const del = async (_id) => {
        try {
            // 二次确认，防止误操作
            if (!window.confirm('确定要删除该订单吗？删除后无法恢复')) {
                return
            }

            // 显示加载提示
            Toast.show({ content: '删除中...', duration: 0 })

            // 调用删除接口
            const res = await deleteOrder(_id)

            // 处理接口响应
            if (res.data.code === 200) {
                Toast.show({ content: '订单删除成功', type: 'success' })
                getData() // 刷新订单列表，移除已删除订单
            } else {
                Toast.show({ content: res.data.message || '删除失败', type: 'fail' })
            }
        } catch (error) {
            // 捕获网络或服务器错误
            console.error('删除订单失败:', error)
            Toast.show({
                content: error.response?.data?.message || '服务器错误，删除失败',
                type: 'fail'
            })
        }
    }
    // 确认收货函数（简化版）
        const tui = async (_id) => {
            try {
                Toast.show({ content: '处理中...', duration: 0 });
                
                const res = await updateOrderStatus(_id, '退款');
                
                Toast.clear();
                console.log(res.data);
                
                if (res.data.code === 200) {
                    Toast.show({ content: '退款成功', type: 'success' });
                    getData();
                }
            } catch (error) {
                Toast.clear();
                Toast.show({ 
                    content: error.response?.data?.message || '操作失败', 
                    type: 'fail' 
                });
            }
        };
    return (
        <div style={{
            backgroundColor: '#f5f5f5',
            minHeight: '100vh',
            fontFamily: 'Arial, sans-serif'
        }}>
            {/* 订单列表 */}
            {list.map(order => {
              if(order.status=="已完成"){
                return  <div key={order._id} style={{
                    backgroundColor: '#fff',
                    margin: `${rem(10)} ${rem(15)}`,
                    borderRadius: rem(4),
                    overflow: 'hidden',
                    border: '1px solid #e0e0e0',
                    height: "50rem",
                    width: "100%"
                }}>
                    {/* 店铺信息 */}
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        padding: `${rem(10)} ${rem(15)}`,
                        borderBottom: '1px solid #f0f0f0',
                    }}>
                        <div style={{
                            width: "10rem",
                            borderRadius: rem(12),
                            backgroundColor: '#f8f8f8',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            marginRight: rem(8)
                        }}>
                            <UserCircleOutline />
                        </div>
                        {
                            shlist.map(ele=>{
                                if(ele._id==order.userId){
                                    return <div style={{ fontSize: "5rem", color: '#333' }} key={ele._id}>{ele.username}</div>
                                }
                            })
                        }
                        
                        <div style={{
                            marginLeft: 'auto',
                            fontSize: "5rem",
                            color: order.status === '待付款' ? '#e52222' :
                                order.status === '已取消' ? '#e52222' :
                                    order.status === '已付款' ? '#52c41a' : '#666',
                            fontWeight: 'bold'
                        }}>{order.status}</div>
                    </div>

                    {/* 商品信息 */}
                    <div style={{
                        display: 'flex',
                        padding: `${rem(15)}`,
                        borderBottom: '1px solid #f0f0f0'
                    }}>
                        <div style={{ marginRight: rem(10) }}>
                            <img src={order.image} alt="商品图片" style={{
                                width: "20rem",
                                borderRadius: rem(4)
                            }} />
                        </div>
                        <div style={{ flex: 1 }}>
                            <div style={{ fontSize: "4rem", color: '#333', marginBottom: rem(5) }}>{order.name}</div>
                            <div style={{ fontSize: "4rem", color: '#999', marginBottom: rem(5) }}>{order.description}</div>
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <div style={{ fontSize: "4rem", color: '#e52222', fontWeight: "bold" }}>¥{order.price}</div>
                                <div style={{ marginLeft: 'auto', fontSize: "4rem", color: '#999' }}>x {order.num}</div>
                            </div>
                        </div>
                    </div>

                    {/* 操作按钮 */}
                    <div style={{
                        display: 'flex',
                        justifyContent: 'flex-end',
                        padding: `${rem(10)} ${rem(15)}`

                    }}>
                        <button style={{
                            marginLeft: rem(10),
                            padding: `${rem(6)} ${rem(12)}`,
                            fontSize: "4rem",
                            borderRadius: rem(4),
                            border: '1px solid #ddd',
                            backgroundColor: '#fff',
                            color: '#333',
                            width: "20rem"
                        }} onClick={() => { tui(order._id) }}>退货退款</button>
                        <button style={{
                            marginLeft: rem(10),
                            padding: `${rem(6)} ${rem(12)}`,
                            fontSize: "4rem",
                            borderRadius: rem(4),
                            border: '1px solid #ddd',
                            backgroundColor: '#fff',
                            color: '#333',
                            width: "20rem"
                        }} onClick={() => { del(order._id) }}>删除订单</button>
                    </div>
                </div>
              }
            })}
        </div>
    );
};

export default Wan;